import java.util.ArrayList;
import java.util.List;

//计算右侧小于当前元素的个数
//测试链接 https://leetcode.cn/problems/count-of-smaller-numbers-after-self/description/
public class CountSmaller {
    int[] helpNums, helpIndex, index, ret;

    public List<Integer> countSmaller(int[] nums) {
        int n = nums.length;
        helpNums = new int[n];
        helpIndex = new int[n];
        index = new int[n];
        ret = new int[n];

        for(int i = 0; i < n; i++){  //index数组与nums数组的每个元素下标绑定
            index[i] = i;
        }

        mergeSort(nums, 0, n-1);


        List<Integer> ans = new ArrayList<>();
        for(int i = 0; i < n; i++){
            ans.add(ret[i]);
        }

        return ans;
    }

    public void mergeSort(int[] nums, int left, int right){
        if(left >= right) return;

        int mid = left + (right - left)/2;

        mergeSort(nums,left,mid);
        mergeSort(nums,mid+1,right);

        int cur1 = left, cur2 = mid+1, i = left;

        while(cur1 <= mid && cur2 <= right){  //降序排列
            if(nums[cur1] <= nums[cur2]){
                helpNums[i] = nums[cur2];
                helpIndex[i++] = index[cur2++];
            }else{
                ret[index[cur1]] += right - cur2 + 1;
                helpNums[i] = nums[cur1];
                helpIndex[i++] = index[cur1++];

            }
        }
        while(cur1 <= mid){
            helpNums[i] = nums[cur1];
            helpIndex[i++] = index[cur1++];
        }
        while(cur2 <= right){
            helpNums[i] = nums[cur2];
            helpIndex[i++] = index[cur2++];
        }

        for(int j = left ; j <= right; j++){
            nums[j] = helpNums[j];
            index[j] = helpIndex[j];
        }
    }
}
